package com.ezone.web.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;

public class ImageTagExportUtil {

	static Logger logger = Logger.getLogger(ImageTagExportUtil.class);

	/**
	 * 读取照片里面的信息
	 * 
	 * @throws IOException
	 * @throws ImageProcessingException
	 */
	public static Map<String, String> exportImageTags(byte[] imgBytes) throws ImageProcessingException, IOException {
		try {
			Metadata metadata = ImageMetadataReader.readMetadata(new ByteArrayInputStream(imgBytes), imgBytes.length);
			Map<String, String> map = new TreeMap<String, String>();
			for (Directory directory : metadata.getDirectories()) {
				for (Tag tag : directory.getTags()) {
					String tagName = tag.getTagName(); // 标签名
					String desc = tag.getDescription(); // 标签信息
					if (tagName.equals("GPS Latitude") || tagName.equals("GPS Longitude")) {
						desc = pointToLatlong(desc);
					}
					map.put(directory.getName() + "→" + tagName, desc);
				}
			}
			logger.info("图片信息解析>>" + JSON.toJSONString(map));
			return map;
		} catch (Exception e) {
			logger.error(e);
			return null;
		}
	}

	public static String pointToLatlong(String point) {
		Double du = Double.parseDouble(point.substring(0, point.indexOf("°")).trim());
		Double fen = Double.parseDouble(point.substring(point.indexOf("°") + 1, point.indexOf("'")).trim());
		Double miao = Double.parseDouble(point.substring(point.indexOf("'") + 1, point.indexOf("\"")).trim());
		Double duStr = du + fen / 60 + miao / 60 / 60;
		return duStr.toString();
	}
}
